package com.ruoyi.mixuebingcheng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.EncryptUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.mixuebingcheng.domain.bo.UserBo;
import com.ruoyi.mixuebingcheng.domain.vo.UserVo;
import com.ruoyi.mixuebingcheng.domain.User;
import com.ruoyi.mixuebingcheng.mapper.WxUserMapper;
import com.ruoyi.mixuebingcheng.service.IUserService;

import java.util.*;

/**
 * 用户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-27
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements IUserService {

    private final WxUserMapper baseMapper;
    private final String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvwUpblCoehKauqT3wygKh+TgQd7AZhfWrX4WPCR9S/wlaUI4ynqK3ybMH80QbjctQrP/QbzQ6BF0qZ7ym/uXdQIDAQABAkA8HBS4iRsrJtWX7DenKt99efFz6POkbNX6TFYU4Oqo0QlKyv9LYdYGjeIHSQ//y0IumSrBGgMq7A/Zw15A2o71AiEA6uskAU1+511F6Pwv9GT786/G3iwqQByrCSJEh4bMFIcCIQDQKYexEnASFJSM7S4eUmeaUz3ZRRTKWx5jaZ7dezAvIwIhALydHOR63zhOGFJvIOWdqvlGGWrKlQWyvtRvkgwqe3LDAiEAr4EEVafc83GEmZjzVD9X+EaMk93pnH7cjSak+cl+I48CIB6XLpoOvkpf4N85srK3f1CqtojoATVn1RWo1RED32+y";
    @Override
    public User wxLogin(User user) {
        User temp = baseMapper.selectByName(user.getName());
        if(Objects.equals(EncryptUtils.decryptByRsa(temp.getPassword(),privateKey), EncryptUtils.decryptByRsa( user.getPassword(),privateKey)))
            return temp;
        return null;
    }

    @Override
    public Boolean insert(User user) {
        User add = BeanUtil.toBean(user, User.class);
        return baseMapper.insert(add)>0;
    }

    /**
     * 查询用户信息
     */
    @Override
    public UserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public TableDataInfo<UserVo> queryPageList(UserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public List<UserVo> queryList(UserBo bo) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<User> buildQueryWrapper(UserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), User::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), User::getPassword, bo.getPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), User::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), User::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getIdNumber()), User::getIdNumber, bo.getIdNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), User::getAvatar, bo.getAvatar());
        lqw.eq(bo.getIsDeleted() != null, User::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增用户信息
     */
    @Override
    public Boolean insertByBo(UserBo bo) {
        User add = BeanUtil.toBean(bo, User.class);
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getName()), User::getName, bo.getName());
        List<UserVo> result = baseMapper.selectVoList(lqw);
        validEntityBeforeSave(add);
        if(!result.isEmpty())
            throw new RuntimeException("用户名重复");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户信息
     */
    @Override
    public Boolean updateByBo(UserBo bo) {
        User update = BeanUtil.toBean(bo, User.class);
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getName()), User::getName, bo.getName());
        List<UserVo> result = baseMapper.selectVoList(lqw);
        validEntityBeforeSave(update);
//        改名后新名找不到
        if(params.get("oldName")!=bo.getName() && result.isEmpty())
            return baseMapper.updateById(update) > 0;
//        不改名能找到原来的
        else if (result.size()==1) {
            return baseMapper.updateById(update) > 0;
        } else
            throw new RuntimeException("用户名重复");

    }

    @Override
    public Boolean qiandao(UserBo bo) {
        User update = BeanUtil.toBean(bo, User.class);
        update.setQiandao(new Date());
        return baseMapper.updateById(update) > 0;

    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(User entity){

    }

    /**
     * 批量删除用户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
